package com.atguigu.jxc.service.impl;

import com.atguigu.jxc.dao.GoodsTypeDao;
import com.atguigu.jxc.domain.ServiceVO;
import com.atguigu.jxc.domain.SuccessCode;
import com.atguigu.jxc.entity.GoodsType;
import com.atguigu.jxc.service.GoodsTypeService;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author zjr
 * @version 1.0
 */
@Service
public class GoodTypeServiceImpl implements GoodsTypeService {
    @Autowired
    GoodsTypeDao goodsTypeDao;
    @Override
    public String loadGoodsType() {
        return getAllGoodsType(-1).toString();
    }

    @Override
    public ServiceVO addType(String goodsTypeName, Integer pId) {
        int goodsTypeState = 0;
        if (pId == -1){
            goodsTypeState = 1;
        }
        goodsTypeDao.add(goodsTypeName,pId,goodsTypeState);
        return new ServiceVO(SuccessCode.SUCCESS_CODE,SuccessCode.SUCCESS_MESS);
    }

    @Override
    public ServiceVO deleteById(Integer goodsTypeId) {
        goodsTypeDao.deleteById(goodsTypeId);
        return new ServiceVO(SuccessCode.SUCCESS_CODE,SuccessCode.SUCCESS_MESS);
    }

    public JsonArray getAllGoodsType(Integer parentId){
        JsonArray array = getGoodsTypeByParentId(parentId);
        for (int i = 0; i < array.size(); i++) {
            JsonObject jsonObject = (JsonObject) array.get(i);
            if (jsonObject.get("state").getAsString().equals("open")){
                continue;
            }else {
                jsonObject.add("children", this.getAllGoodsType(jsonObject.get("id").getAsInt()));
            }
        }
        return array;
    }

    private JsonArray getGoodsTypeByParentId(Integer parentId) {
        List<GoodsType> goodsList = goodsTypeDao.getGoodsTypeByParentId(parentId);
        JsonArray array = new JsonArray();
        for (GoodsType goodsType : goodsList) {
            JsonObject obj = new JsonObject();
            obj.addProperty("id",goodsType.getGoodsTypeId());
            obj.addProperty("text",goodsType.getGoodsTypeName());
            if (goodsType.getGoodsTypeState()==1){
                obj.addProperty("state","closed");
            }else{
                obj.addProperty("state","open");
            }
            obj.addProperty("iconCls", "goods-type");
            JsonObject attributes = new JsonObject();
            attributes.addProperty("state", goodsType.getGoodsTypeState());
            obj.add("attributes", attributes);
            array.add(obj);
        }
        return array;
    }
}
